package com.nova.auth.controller.wx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nova.base.utils.HttpUtils;
import com.nova.base.utils.SHA1;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

import static com.nova.auth.constant.Constants.*;

/**
 * @author ttao
 * @since 2024/10/19 12:58
 */
@RestController
@Slf4j
public class CallBackController {
    // /**
    //  * 回调消息校验
    //  *
    //  * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
    //  * @param timestamp 时间戳
    //  * @param nonce     随机数
    //  * @param echostr   随机字符串
    //  * @return
    //  */
    // @GetMapping("callback")
    // public String callback(@RequestParam("signature") String signature,
    //                        @RequestParam("timestamp") String timestamp,
    //                        @RequestParam("nonce") String nonce,
    //                        @RequestParam("echostr") String echostr) {
    //     log.info("get验签请求参数:signature:{}, timestamp:{}, nonce:{}, echostr:{}", signature, timestamp, nonce, echostr);
    //     String shaStr = SHA1.getSHA1(TOKEN, timestamp, nonce, "");
    //     if (signature.equals(shaStr)) {
    //         return echostr;
    //     }
    //     return "unknown";
    // }

    @GetMapping("/callback")
    public String callback(HttpServletRequest request) {
        String code = request.getParameter("code");
        String state = request.getParameter("state");
        log.info("wechat授权跳转参数 code:{}, state:{}", code, state);

        // 根据code获取网页授权access_token

        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APP_ID + "&secret=" + APP_SECRET +
                "&code=" + code + "&grant_type=authorization_code";
        String s = HttpUtils.httpGet(url);
        JSONObject jsonObject = (JSONObject) JSON.parse(s);
        log.info("tokenInfo:{}", jsonObject);

        Object accessToken = jsonObject.get("access_token");
        Object openid = jsonObject.get("openid");
        // 拉取用户信息

        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" + accessToken + "&openid=" +
                openid + "&lang=zh_CN";
        String response = HttpUtils.httpGet(requestUrl);
        JSONObject userInfo = (JSONObject) JSON.parse(response);
        log.info("WxUserinfo:{}", userInfo);

        return "不在你左右，却被你左右。";
    }
}
